/**
 * This class acts as control message UDP client for the 
 * coordinator. This is used by ElectionSubSystem and 
 * FailureDetector. 
 */
package com.comp6231.coordinator;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;

/**
 * @author Farzana Alam
 * 
 */
public class ControlUDPClient {
	DatagramSocket socket = null;

	public String sendPacket(String hostName, String UDPPort, String message) {

		try {
			socket = new DatagramSocket();
			byte[] messageBytes = message.getBytes();
			InetAddress address = InetAddress.getByName(hostName);

			DatagramPacket request = new DatagramPacket(messageBytes,
					message.length(), address, new Integer(UDPPort));
			socket.send(request);

			// after 5 seconds if no reply it will consider as there was no
			// response from the other replica coordinator
			socket.setSoTimeout(5000);

			byte[] buffer = new byte[1000];
			DatagramPacket reply = new DatagramPacket(buffer, buffer.length);

			String replyMessage = "";

			try {
				socket.receive(reply);
				replyMessage = new String(reply.getData()).trim();
			} catch (SocketTimeoutException e) {
				replyMessage = new String("no response");
			}

			return replyMessage;
		} catch (SocketException e) {
			e.printStackTrace();
			return "";
		} catch (IOException e) {
			e.printStackTrace();
			return "";
		} finally {
			if (socket != null)
				socket.close();
		}

	}
}
